#!/usr/bin/python3
# coding=utf-8
from flask import Flask, request, jsonify, send_from_directory, render_template, redirect, url_for

import json
from src.gps_transfer import GPSTransfer
from src.gps_transfer import GPSTransferType

import time
import os
import base64

app = Flask(__name__)


@app.route('/')
def hello_world():
    return "Hello World"


@app.route('/transfer/location_transfer')
def gps_transfer():

    default_response = {'code': 1,
                        'status': 200,
                        'data': None
                        }

    transfer_type_from = request.args.get('from')
    transfer_type_to = request.args.get('to')
    location = {}
    location['log'] = request.args.get('log')
    location['lat'] = request.args.get('lat')

    from_type = GPSTransferType.get_transfer_type(transfer_type_from)
    to_type = GPSTransferType.get_transfer_type(transfer_type_to)

    default_response['data'] = GPSTransfer().location_transfer(
        location, from_type, to_type)

    return json.dumps(default_response, ensure_ascii=False)

# 上传文件


UPLOAD_FOLDER = 'upload'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
basedir = os.path.abspath(os.path.dirname(__file__))
ALLOWED_EXTENSIONS = set(['txt'])
# 用于判断文件后缀


def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS


def save_file(f):

    file_dir = os.path.join(basedir, app.config['UPLOAD_FOLDER'])
    if not os.path.exists(file_dir):
        os.makedirs(file_dir)

    fname = f.filename
    print(fname)
    ext = fname.rsplit('.', 1)[1]  # 获取文件后缀
    unix_time = int(time.time())
    new_filename = str(unix_time)+'.'+ext
    f.save(os.path.join(file_dir, new_filename))  # 保存文件到upload目录
    return {'filename': new_filename}


def get_download_file(filenname):
    names = filenname.rsplit('.', 1)
    return names[0]+'_out.'+names[1]


@app.route('/file_upload', methods=['POST'], strict_slashes=False)
def file_upload():
    file_dir = os.path.join(basedir, app.config['UPLOAD_FOLDER'])
    if not os.path.exists(file_dir):
        os.makedirs(file_dir)

    f = request.files['upload_file']

    if f and allowed_file(f.filename):  # 判断是否是允许上传的文件类型
        fname = f.filename
        print(fname)
        ext = fname.rsplit('.', 1)[1]  # 获取文件后缀
        unix_time = int(time.time())
        new_filename = str(unix_time)+'.'+ext
        f.save(os.path.join(file_dir, new_filename))  # 保存文件到upload目录
        return json.dumps({"errno": 0, "errmsg": "上传成功", "token": new_filename})
    else:
        return json.dumps({"errno": 1001, "errmsg": "上传失败"})


def get_file_name(file_path):
    return file_path.rsplit('/', 1)[1]


@app.route('/transfer_file', methods=['POST', 'GET'], strict_slashes=False)
def transfer_file():
    response = {'code': 1000}
    data = request.get_data()
    json_data = json.loads(data.decode('utf-8'))

    file_in = json_data.get('file_in')
    file_dir = os.path.join(basedir, app.config['UPLOAD_FOLDER'])

    if isinstance(file_in, str):
        file_path = os.path.join(file_dir, file_in)
    transfer_type_from = json_data.get('from')
    transfer_type_to = json_data.get('to')

    if not os.path.exists(file_path):
        response['error'] = "待转换文件找不到！请联系管理员"
        return json.dumps(response)

    from_type = GPSTransferType.get_transfer_type(transfer_type_from)
    to_type = GPSTransferType.get_transfer_type(transfer_type_to)

    file_path_out = get_download_file(file_path)
    file_path_out = GPSTransfer().transfer_file(file_path,
                                                file_path_out,
                                                from_type,
                                                to_type)

    response = {'code': 1000}
    response['data'] = file_path_out
    if os.path.isfile(file_path_out):
        file_name = get_file_name(file_path_out)
        response['file_name'] = file_name

    return json.dumps(response)


def download_file(fname):
    fpath = os.path.join(basedir, app.config['UPLOAD_FOLDER'])  # 获取文件路径
    if fname.strip() and fpath.strip():
        print(fname, fpath)
        if os.path.isfile(os.path.join(fpath, fname)) and os.path.isdir(fpath):
            # 返回要下载的文件内容给客户端
            return send_from_directory(fpath, fname, as_attachment=True)
        else:
            return '{"msg":"参数不正确"}'
    else:
        return '{"msg":"请输入参数"}'


@app.route('/file_download', methods=['get'])
def download():
    fname = request.values.get('filename', '')  # 获取文件名
    return download_file(fname)


if __name__ == '__main__':
    app.run(debug=True, port='5050')
